package a2022.a20220905;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lenovo
 * @date 2022/9/5
 */
public class Codec {
    public static void main(String[] args) {
        TreeNodeTwo root = new TreeNodeTwo(1);
        root.left = new TreeNodeTwo(2);
        root.right = new TreeNodeTwo(3);
        root.right.left = new TreeNodeTwo(4);
        root.right.right = new TreeNodeTwo(5);
        deserialize(serialize(root));
    }

    public static String serialize(TreeNodeTwo root) {
        return rserialize(root, "");
    }

    public static TreeNodeTwo deserialize(String data) {
        String[] dataArray = data.split(",");
        List<String> dataList = new LinkedList<String>(Arrays.asList(dataArray));
        return rdeserialize(dataList);
    }

    public static String rserialize(TreeNodeTwo root, String str) {
        if (root == null) {
            str += "None,";
        } else {
            str += str.valueOf(root.val) + ",";
            str = rserialize(root.left, str);
            str = rserialize(root.right, str);
        }
        return str;
    }

    public static TreeNodeTwo rdeserialize(List<String> dataList) {
        if (dataList.get(0).equals("None")) {
            dataList.remove(0);
            return null;
        }

        TreeNodeTwo root = new TreeNodeTwo(Integer.valueOf(dataList.get(0)));
        dataList.remove(0);
        root.left = rdeserialize(dataList);
        root.right = rdeserialize(dataList);

        return root;
    }
}

